package com.dljd.demo;

import com.dljd.constant.MqConstant;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.junit.Test;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author limin
 * @date 2025-06-15 23:45
 * @description
 */
public class EBatchTest {
    @Test
    public void testBatchProducer() throws Exception{
        //创建一个生产者(指定一个组名)
        DefaultMQProducer producer = new DefaultMQProducer("batch-producer-group");
        //连接namesrv
        producer.setNamesrvAddr(MqConstant.NAME_SRV_ADDR);
        //启动
        producer.start();  //以上为建立连接
        //创建一个批量消息（是放在了同一个消息队列里）
        List<Message> msgs = Arrays.asList(
                new Message("batchTopic","我是一组消息的A消息".getBytes()),
                new Message("batchTopic","我是一组消息的B消息".getBytes()),
                new Message("batchTopic","我是一组消息的B消息".getBytes())
        );
        //发送消息
        SendResult send = producer.send(msgs);
        System.out.println(send);
        System.out.println(send.getSendStatus());
        //关闭生产者
        producer.shutdown();
    }

    @Test
    public void batchConsumer() throws Exception{
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("batch-consumer-group");
        consumer.setNamesrvAddr(MqConstant.NAME_SRV_ADDR);
        consumer.subscribe("batchTopic", "*");
        consumer.registerMessageListener(new MessageListenerConcurrently(){
            //是3个消息捆绑在一起发送的，但是消费的时候，消费一次就相当于消费3条消息
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                System.out.println("收到消息了" + new Date());
                System.out.println(msgs.size());
                System.out.println(new String(msgs.get(0).getBody()));
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        consumer.start();
        System.out.println("我先执行");
        System.in.read();
    }
}
